<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 商品列表区域 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        class="tree-table"
        ref="treeRef"
        ><template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: lightgreen"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editCateDialog(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeCate(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="cateSizeChange"
        @current-change="cateCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加分类对话框区域 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="resetAddCateForm"
    >
      <!-- 添加分类内容区域 -->
      <el-form
        :model="addCateForm"
        :rules="addCaterules"
        ref="addCateRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- 级联选择框区域 -->
          <el-cascader
            v-model="selectedKeys"
            :options="optCateList"
            :props="{
              expandTrigger: 'hover',
              label: 'cat_name',
              value: 'cat_id',
              children: 'children',
            }"
            :show-all-levels="false"
            @change="parentCateChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框区域 -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateClose"
    >
      <el-form
        :model="editCateForm"
        :rules="addCaterules"
        ref="editCateRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendEditCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
    
<script>
export default {
  data() {
    return {
      //商品分类请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品分类数据
      cateList: [],

      //商品分类个数
      total: 0,

      //指定表格列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },

        {
          label: "是否有效",
          type: "template", //将当前列定义为模板列
          template: "isOk", //表示当前列使用模板名称
        },
        {
          label: "排序",
          type: "template", //将当前列定义为模板列
          template: "order", //表示当前列使用模板名称
        },
        {
          label: "操作",
          type: "template", //将当前列定义为模板列
          template: "opt", //表示当前列使用模板名称
        },
      ],
      addCateDialogVisible: false, // 添加分类对话框显示与隐藏
      // 添加分类表单数据
      addCateForm: {
        cat_name: "",
        cat_level: 0,
        cat_pid: 0,
      },

      // 选中的父级分类id数组
      selectedKeys: [],

      //级联选择框数据
      optCateList: [],

      // 编辑分类对话框显示与隐藏
      editCateDialogVisible: false,

      // 编辑分类数据
      editCateForm: {
        cat_name: "",
        cat_id: 0,
      },

      // 添加分类表单验证规则
      addCaterules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品失败");
      }
      this.cateList = res.data.result;
      this.total = res.data.total;
      //   console.log(res);
    },
    // 监听 pageSize 变化
    cateSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      // console.log(newSize)
      this.getCateList();
    },
    // 监听 pagenum 变化
    cateCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getCateList();
    },

    // 添加分类对话框
    async showAddCateDialog() {
      //获取级联选择框数据
      const { data: res } = await this.$http.get("categories", {
        params: {
          type: 2,
        },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("请求父级分类失败");
      }
      this.optCateList = res.data;
      //   console.log(this.optCateList);
      this.addCateDialogVisible = true;
    },

    // 监听对话框关闭事件 重置表单
    resetAddCateForm() {
      this.$refs.addCateRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_level = 0;
      this.addCateForm.cat_pid = 0;
    },

    // 级联选择框选择项发生变化触发
    parentCateChange() {
      // console.log(this.selectedKeys);
      // 如果 selectedKeys 大于0 说明选中了父级分类 小于0 说明未选中任何分类
      if (this.selectedKeys.length > 0) {
        // console.log(this.selectedKeys);
        this.addCateForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1];
        this.addCateForm.cat_level = this.selectedKeys.length;
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
    },

    // 点击确定发送添加分类数据
    addCate() {
      // 请求前表单预验证
      this.$refs.addCateRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.info("请检查添加内容后重试");
        }
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加分类失败");
        }
        this.$message.success("添加分类成功");
        this.getCateList();
        this.addCateDialogVisible = false;
      });
    },

    // 点击编辑弹出对话框
    editCateDialog(editInfo) {
      this.editCateDialogVisible = true;
      this.editCateForm.cat_name = editInfo.cat_name;
      this.editCateForm.cat_id = editInfo.cat_id;
    },

    // 监听编辑分类对话框关闭事件
    editCateClose() {
      this.$refs.editCateRef.resetFields();
    },

    // 点击确定 发送编辑分类请求
    sendEditCate() {
      //请求发送前 表单预验证
      this.$refs.editCateRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.info("请检查内容后重试");
        }
        const { data: res } = await this.$http.put(
          "categories/" + this.editCateForm.cat_id,
          { cat_name: this.editCateForm.cat_name }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("编辑分类失败");
        }
        this.$message.success("编辑分类成功");
        this.getCateList();

        this.editCateDialogVisible = false;
      });
    },

    //点击删除 移除当前分类
    async removeCate(cateInfo) {
      //询问用户是否确认删除
      const info = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (info === "cancel") {
        return this.$message.info("已取消删除");
      }
      const res = await this.$http.delete("categories/" + cateInfo.cat_id);
      console.log(res);
      if (res.status !== 200) {
        return this.$message.error("删除分类失败");
      }
      this.$message.success("删除分类成功");
      this.getCateList();
    },
  },
};
</script>
    
<style lang='less' scoped>
.tree-table {
  margin-top: 15px;
}

.el-cascader {
  display: block;
}
</style>